//
//  RxUtilites.swift
//  hrhtv
//
//  Created by Ink on 2025-07-09.
//

import RxSwift
import RxCocoa

// MARK: - ObservableType

public extension ObservableType {

    /// 自动在 owner 释放前绑定，简化绑定写法
//    func bindUntil(_ owner: NSObject) -> Observable<Element> {
//        self.take(until: owner.rx.deallocated)
//    }
    func bindUntil<T: AnyObject & ReactiveCompatible>(_ owner: T) -> Observable<Element> {
        self.take(until: owner.rx.deallocated)
    }

    /// 自动 `[weak owner]` 捕获 + 生命周期解绑
    func bindWeak<T: NSObject>(_ owner: T, to binder: @escaping (T, Element) -> Void) -> Disposable {
        return self
            .take(until: owner.rx.deallocated)
            .subscribe(onNext: { [weak owner] value in
                guard let owner else { return }
                binder(owner, value)
            })
    }

    /// 自动绑定到 Binder（如 label.rx.text），自动释放
    func bind<T: ObserverType>(to binder: T, until owner: NSObject) where T.Element == Element {
        self
            .take(until: owner.rx.deallocated)
            .bind(to: binder)
            .disposed(by: owner.rxDisposeBag)
    }
}

// MARK: - Single

public extension PrimitiveSequence where Trait == SingleTrait {
    func bindUntil(_ owner: NSObject) -> Single<Element> {
        self.asObservable()
            .take(until: owner.rx.deallocated)
            .asSingle()
    }
}

// MARK: - Maybe

public extension PrimitiveSequence where Trait == MaybeTrait {
    func bindUntil(_ owner: NSObject) -> Maybe<Element> {
        self.asObservable()
            .take(until: owner.rx.deallocated)
            .asMaybe()
    }
}

// MARK: - Completable

public extension PrimitiveSequence where Trait == CompletableTrait {
    func bindUntil(_ owner: NSObject) -> Completable {
        self.asObservable()
            .take(until: owner.rx.deallocated)
            .ignoreElements()
            .asCompletable() // 转换回 Completable
    }
}

